package cn.chenhao.pay.controller;

import cn.chenhao.order.domain.AdoptOrder;
import cn.chenhao.order.service.IAdoptOrderService;
import cn.chenhao.pay.constants.AlipayConfig;
import cn.chenhao.pay.constants.PayConstants;
import cn.chenhao.pay.domain.AlipayInfo;
import cn.chenhao.pay.domain.PayBill;
import cn.chenhao.pay.service.IAlipayInfoService;
import cn.chenhao.pay.service.IPayBillService;
import cn.chenhao.quartz.constants.JobConstants;
import cn.chenhao.quartz.service.IQuartzService;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Api(tags = "支付接口", description = "支付接口接口详细描述")
@RequestMapping
@RestController
public class AlipayController {

    @Autowired
    private IPayBillService payBillService;

    @Autowired
    private IAlipayInfoService alipayInfoService;

    @Autowired
    private IAdoptOrderService adoptOrderService;

    @Autowired
    private IQuartzService quartzService;

    @PostMapping("/notify")
    public void notify(HttpServletRequest request) {
        try {
            //获取支付宝POST过来反馈信息
            Map<String, String> params = new HashMap<String, String>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
                String name = (String) iter.next();
                String[] values = (String[]) requestParams.get(name);
                String valueStr = "";
                for (int i = 0; i < values.length; i++) {
                    valueStr = (i == values.length - 1) ? valueStr + values[i]
                            : valueStr + values[i] + ",";
                }
                //乱码解决，这段代码在出现乱码时使用
                params.put(name, valueStr);
            }

            String unionPaysn = params.get("out_trade_no");
            PayBill payBill = payBillService.queryByUnionPaySn(unionPaysn);
            if (payBill != null) {
                AlipayInfo info = alipayInfoService.getByShopId(payBill.getShop_id());


                /* 验证签名 */
                boolean signVerified = AlipaySignature.rsaCheckV1(
                        params,
                        info.getAlipay_public_key(),
                        AlipayConfig.charset,
                        AlipayConfig.sign_type); //调用SDK验证签名

                if (signVerified) {// 如果验证成功
                    // 就修改商户订单号
                    String out_trade_no = request.getParameter("out_trade_no");

                    // 支付宝交易号
                    String trade_no = request.getParameter("trade_no");

                    //交易状态
                    String trade_status = request.getParameter("trade_status");

                    if (trade_status.equals("TRADE_FINISHED")) {//

                    } else if (trade_status.equals("TRADE_SUCCESS")) {// 支付成功后。。。
                        // 修改当前支付单的状态
                        payBill.setState(1);
                        payBillService.update(payBill);
                        // 记录支付流水

                        // 修改业务库的业务订单状态
                        if(PayConstants.BUSINESS_TYPE_ADOPT.equals(payBill.getBusinessType())){

                            AdoptOrder order = adoptOrderService.findById(payBill.getBusinessKey());

                            order.setState(1);

                            adoptOrderService.update(order);
                            // 支付完成后，支付超时取消任务自动取消
                            String jobName = JobConstants.PAY_OVER_TIME_ADOPT_ORDER + order.getId();
                            quartzService.removeJob(jobName);
                        } else if(PayConstants.BUSINESS_TYPE_PRODUCT.equals(payBill.getBusinessType())){
                            
                        }

                    }
                }
            }
        }
        catch (AlipayApiException e) {
            e.printStackTrace();
        }
        catch (Exception e) {
            e.printStackTrace();
        }

        System.err.println("异步回调");
    }


}
